import axios from 'axios'
import Qs from 'qs'
import router from '@/router'
import Vue from 'vue';
import { Toast } from 'vant';
Vue.use(Toast);
const serve = axios.create({
	baseURL: '',// process.env.VUE_APP_SERVE_URL,
	timeout: 10000,//10秒超时
	headers: {
		'Content-Type': 'application/json' 
	}
})
serve.defaults.transformRequest = [function(data, headers) {
	const isType = data && data.isToken ? true : ''
	if (data !== undefined && !(data instanceof FormData)) {
		const contentType = headers['Content-Type']
		if (contentType.includes('application/json')) {
			data = JSON.stringify(data)
		} else if (
			contentType.includes('application/x-www-form-urlencoded')
		) {
			data = Qs.stringify(data)
		}
	}
	// 设置token
	const access_token = localStorage.getItem('Token')
	if (access_token && !isType) {
		headers.common ? headers.common['JYB-Token'] = access_token : headers.common = {
			'JYB-Token': access_token
		}
	}
	return data;
}]
//拦截器
serve.interceptors.request.use(
	config => config,
	error => {
		return Promise.reject(error)
	}
)

// 是否已经弹出了登录过期窗口
serve.interceptors.response.use(
	res => {
		const data = res.data;
		// code === 601 token无效
		if(data.code === 601){
			Toast({
				message: data.msg,
				position: 'bottom'
			})
			setTimeout(()=> {
				router.push({
					path: '/Login',
					query: {}
				});
			}, 1500);
			return
		}
		if (!data.code || data.code === 200) {
			return data
		} else {
			return data
		}
	},
	error => {
		try {
			const err = error.response.data;
			if (typeof err === 'string') {} else if (typeof err === 'object') {}
		} catch (error) {
			//Toast('服务异常');
		}
		return Promise.reject(error)
	}
)

export {
	serve
}
